package inits

import (
	"context"
	"coroutine/server/basic/config"
	"fmt"
	"github.com/go-redis/redis/v8"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
)

func init() {
	InitConfig()
	InitMysql()
	InitRedis()
}
func InitConfig() {
	viper.SetConfigFile("D:\\goWork\\src\\coroutine\\server\\basic\\dev.yaml")
	err := viper.ReadInConfig()
	if err != nil {
		panic("viper配置读取失败")
	}
	log.Println("viper配置读取成功")
	err = viper.Unmarshal(&config.AppConf)
	if err != nil {
		panic("viper配置解析失败")
	}
	log.Println("viper配置解析成功", config.AppConf)
}

func InitMysql() {
	AppConf := config.AppConf.Mysql
	var err error
	dsn := fmt.Sprintf("%v:%v@tcp(%v:%v)/%v?charset=utf8mb4&parseTime=True&loc=Local", AppConf.User, AppConf.Password, AppConf.Host, AppConf.Port, AppConf.DataBase)
	config.DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info),
	})
	if err != nil {
		panic("mysql 连接失败")
	}
	log.Println("mysql 连接成功", config.DB, dsn)
}

func InitRedis() {
	AppConf := config.AppConf.Redis
	ctx := context.Background()
	config.Rdb = redis.NewClient(&redis.Options{
		Addr:     AppConf.Addr,     // use default Addr
		Password: AppConf.Password, // no password set
		DB:       AppConf.Db,       // use default DB
	})
	err := config.Rdb.Ping(ctx).Err()
	if err != nil {
		panic("redis 连接失败")
	}
	log.Println("redis 连接成功", config.Rdb)
}
